package config

import (
	"fmt"

	"github.com/spf13/viper"
	"gopkg.in/yaml.v2"
)

type Config struct {
	Service
	License
	Log
}

type Service struct {
	HTTPAddr              string `mapstructure:"http_addr" yaml:"http_addr"`
	GRPCAddr              string `mapstructure:"grpc_addr" yaml:"grpc_addr"`
	EnableConcurrentLimit int    `mapstructure:"enable_concurrent_limit" yaml:"enable_concurrent_limit"`
	MaxConcurrent         int    `mapstructure:"max_concurrent" yaml:"max_concurrent"`
}

type License struct {
	LicenseType    string `mapstructure:"http_addr" yaml:"http_addr"`
	LicenseKeyFile string `mapstructure:"license_key_file" yaml:"license_key_file"`
	PublicKeyFile  string `mapstructure:"public_key_file" yaml:"public_key_file"`
	Option         map[string]string
}

type Log struct {
	Level   string `mapstructure:"level" yaml:"level"`
	Context struct {
		Format     string            `mapstructure:"format" yaml:"format"`
		ShowCaller bool              `mapstructure:"show_caller" yaml:"show_caller"`
		Fileds     map[string]string `mapstructure:"fileds" yaml:"fileds"`
	} `mapstructure:"context" yaml:"context"`
	Output struct {
		Compress   bool   `mapstructure:"compress" yaml:"compress"`
		Console    bool   `mapstructure:"console" yaml:"console"`
		File       bool   `mapstructure:"file" yaml:"file"`
		FilePath   string `mapstructure:"file_path" yaml:"file_path"`
		MaxAge     int    `mapstructure:"max_age" yaml:"max_age"`
		MaxBackups int    `mapstructure:"format" yaml:"format"`
		MaxSize    int    `mapstructure:"max_backups" yaml:"max_backups"`
	} `mapstructure:"output" yaml:"output"`
}

var C Config

func Initialize() {
	v := viper.New()
	v.SetConfigName("service")
	v.AddConfigPath(".")
	v.SetConfigType("yml")
	if err := v.ReadInConfig(); err != nil {
		panic("initialize config" + err.Error())
	}

	if err := v.Unmarshal(&C); err != nil {
		panic("unmarshal config" + err.Error())
	}

	C.show()
}

func (c Config) show() {
	config := fmt.Sprintf(`
-----------------------------------------------------------------------------------------
%v
-----------------------------------------------------------------------------------------
`, c)

	fmt.Println(config)
}

func (c Config) String() string {
	if b, err := yaml.Marshal(c); err == nil {
		return string(b)
	}
	return ""
}
